package es.puravida.watchuoc.util;

import java.io.InputStream;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.impl.conn.SingleClientConnManager;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import es.puravida.watchuoc.R;
import es.puravida.watchuoc.WatchUOCApplication;
import es.puravida.watchuoc.service.WatchUOCService;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;

public class MyHTTPClient extends DefaultHttpClient {

	private static final String TAG = MyHTTPClient.class.getName();
	
	final WatchUOCApplication context;

	private BasicCookieStore almacenCookies = new BasicCookieStore();

	private String sessionUOC;

	public MyHTTPClient(WatchUOCApplication context) {
		this.context = context;
		SharedPreferences settings = context.getSharedPreferences("watchuoc",
				context.MODE_PRIVATE);
		String proxy = settings.getString("proxy", "");
		if (!"".equals(proxy)) {
			Integer port = null;
			if (proxy.indexOf(":") != -1) {
				port = Integer
						.parseInt(proxy.substring(proxy.indexOf(":") + 1));
				proxy = proxy.substring(0, proxy.indexOf(":"));
			}
			HttpHost httpproxy = new HttpHost(proxy, port);
			this.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
					httpproxy);
		}
	}

	@Override
	protected ClientConnectionManager createClientConnectionManager() {
		SchemeRegistry registry = new SchemeRegistry();
		registry.register(new Scheme("http", PlainSocketFactory
				.getSocketFactory(), 80));
		registry.register(new Scheme("https", newSslSocketFactory(), 443));
		return new SingleClientConnManager(getParams(), registry);
	}

	private SSLSocketFactory newSslSocketFactory() {
		try {
			// Get an instance of the Bouncy Castle KeyStore format
			KeyStore trusted = KeyStore.getInstance("BKS");
			InputStream in = context.getResources().openRawResource(
					R.raw.mykeystore);
			try {
				trusted.load(in, "password".toCharArray());
			} finally {
				in.close();
			}
			SSLSocketFactory sf = new SSLSocketFactory(trusted);
			// Hostname verification from certificate
			// http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506
			sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
			return sf;
		} catch (Exception e) {
			throw new AssertionError(e);
		}
	}

	public String getSessionUOC() {
		return sessionUOC;
	}

	public void setSessionUOC(String sessionUOC) {
		this.sessionUOC = sessionUOC;
	}

	public String doPost(String sUrl, List<NameValuePair> list) {
		try {
			HttpPost httpost = new HttpPost(sUrl);
			HttpConnectionParams.setConnectionTimeout(httpost.getParams(),
					10000);
			httpost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));

			HttpResponse response = execute(httpost);
			HttpEntity entity = response.getEntity();

			String sPage = convertPage(EntityUtils.toString(entity));
			return sPage;
		} catch (Exception e) {
			Log.e(TAG,e.getMessage(),e);
			return null;
		}
	}

	public String doGet(String sUrl, List<NameValuePair> list) {
		try {
			String url = sUrl;
			url += "?";
			for (NameValuePair vp : list) {
				url += vp.getName() + "=" + vp.getValue() + "&";
			}
			HttpGet httpget = new HttpGet(url);
			HttpConnectionParams.setConnectionTimeout(httpget.getParams(),
					10000);

			HttpResponse response = execute(httpget);
			HttpEntity entity = response.getEntity();

			String sPage = convertPage(EntityUtils.toString(entity));
			return sPage;
		} catch (Exception e) {
			Log.e(TAG,e.getMessage(),e);
			return null;
		}
	}

	private String convertPage(String sPage) {
		sPage = sPage.replaceAll("Ã¡", "á");
		sPage = sPage.replaceAll("Ã©", "é");
		sPage = sPage.replaceAll("Ã­", "í");
		sPage = sPage.replaceAll("Ã³", "ó");
		sPage = sPage.replaceAll("Ãº", "ú");
		sPage = sPage.replaceAll("Ã±", "ñ");
		sPage = sPage.replaceAll("ÃÃ¡", "Á");
		sPage = sPage.replaceAll("ÃÃ©", "É");
		sPage = sPage.replaceAll("ÃÃ­", "Í");
		sPage = sPage.replaceAll("ÃÃ³", "Ó");
		sPage = sPage.replaceAll("ÃÃº", "Ú");
		sPage = sPage.replaceAll("ÃÃ±", "Ñ");
		return sPage;
	}
}